﻿using GenericPersistance;
using LiveLinkExporter;
using SharePointPersistence;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Linq;

namespace LLTreeManagementApplication.Dialog
{
    public partial class LiveLinkMappingConverter : Form
    {
        ProjectParameter _projectParameter = null;
        TreeView _exportTree = null;
        int _folderId = -1;
        List<Update> _updateItems = new List<Update>();
        //string _savePath = "";

        public LiveLinkMappingConverter()
        {
            InitializeComponent();
            dgwConverterResults.CellFormatting += dataGridView_CellFormatting;
            dgwConverterResults.AutoGenerateColumns = false;
            //dgwConverterResults.DataSource = _updateItems;

        }

        void dataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (_updateItems.Count > 0 && dgwConverterResults.Columns[e.ColumnIndex].Name == "Status")
            {

                var update = _updateItems[e.RowIndex];

                //var action = dgwConverterResults[e.ColumnIndex, e.RowIndex].Value;

                if (update.MessageType == MessageType.Error)
                {
                    e.Value = Resource.Error_red_16x16;
                }
                else if (update.MessageType == MessageType.Info)
                {
                    e.Value = Resource.StatusAnnotations_Complete_and_ok_16xLG_color;
                }
                else
                {
                    e.Value = Resource.StatusAnnotations_Help_and_inconclusive_16xLG_color;
                }
            }
        }

        public DialogResult ShowDialog(ProjectParameter projectParameter, TreeView exportTree)
        {
            _projectParameter = projectParameter;
            _exportTree = exportTree;
            _folderId = projectParameter.SelectedSharePointItemId;

            return this.ShowDialog();
        }

        private string CheckOrCreateApplicationFolder()
        {
            string appFolder = Path.GetTempPath() + "MappingTool";

            if (!System.IO.Directory.Exists(appFolder))
            {
                Directory.CreateDirectory(appFolder);
            }
            return appFolder;
        }

        private void btnConvert_Click(object sender, EventArgs e)
        {
            //var folder = @"C:\Common_Libs\_net\MigrationMapper\testdata\origExport";

            OpenFileDialog dlg = new OpenFileDialog();
            dlg.RestoreDirectory = true;
            dlg.Filter = "Tzunami Exporter File|*.tdx";
            dlg.Title = "Select the original Tzunami Exporter File";
            
            //FolderBrowserDialog dlg = new FolderBrowserDialog();
            //dlg.ShowNewFolderButton = true;
            //dlg.Description = "Select the target folder, will contain the new structure and files";
            //dlg.SelectedPath = _savePath != "" ? _savePath : "";
            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                var folder = @"C:\Common_Libs\_net\MigrationMapper\testdata\origExportDelta";
                try
                {
                    Cursor.Current = Cursors.WaitCursor;
                    //SharePoint2010Persistence instance = new SharePoint2010Persistence();
                    //instance.ProgressInit += ProgressInit;
                    //instance.ProgressUpdate += ProgressUpdate;
                    //folder = instance.LoadZipFileAndExtractToUserFolder(ConfigurationManager.AppSettings["ImportStructureFile"], _folderId);

                    _updateItems.Clear();
                    dgwConverterResults.DataSource = null;

                    //_savePath = dlg.SelectedPath;

                    Exporter exp = new Exporter(_projectParameter, DateTime.Now.ToString("dMMyyyy_HHmmss"));
                    exp.ProcessUpdate += exp_ProcessUpdate;
                    exp.Export(Path.GetDirectoryName(dlg.FileName), Path.GetDirectoryName(dlg.FileName), _exportTree);
                }
                catch (Exception ex)
                {
                    _updateItems.Add(new Update() { Information = ex.Message + ex.StackTrace, MessageType = MessageType.Error });
                }
                finally
                {
                    //if (folder != "") Directory.Delete(folder, true);
                    dgwConverterResults.DataSource = _updateItems;
                    btnExportLog.Enabled = true;
                    Cursor.Current = Cursors.Default;
                }
            }
        }

        void exp_ProcessUpdate(object sender, Update update)
        {
            _updateItems.Add(update);
        }

        private void ProgressUpdate(object sender, long currentStep)
        {
            //throw new NotImplementedException();
        }

        private void ProgressInit(object sender, long stepCount, string name)
        {
            //throw new NotImplementedException();
        }

        private void btnExportLog_Click(object sender, EventArgs e)
        {

            SaveFileDialog saveDlg = new SaveFileDialog();
            saveDlg.RestoreDirectory = true;
            saveDlg.Filter = "XML File|*.xml";
            saveDlg.Title = "Select a xml file";

            if (saveDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                XElement el = new XElement("Log",
                       new XElement("MigrationSolutionMapper",
                           new XAttribute("type", "LiveLink"),
                           new XAttribute("version", "2.1 API")));
                var logEntries = new XElement("LogEntries");
                el.Add(logEntries);

                foreach (var update in _updateItems)
                {
                    XElement log = new XElement("Log", new XAttribute("type", update.MessageType), update.Information);
                    logEntries.Add(log);
                }

                el.Save(saveDlg.FileName);
            }


        }

        //private void btnSelectOrigFileFolder_Click(object sender, EventArgs e)
        //{
        //    FolderBrowserDialog dlg = new FolderBrowserDialog();
        //    dlg.ShowNewFolderButton = true;
        //    dlg.Description = "Select the original export folder contains the tdx files";

        //    if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        //    {
        //        lblOrigFileFolder.Text = dlg.SelectedPath;
        //        btnConvert.Enabled = true;
        //    }
        //}


    }
}
